import 'dart:developer';
import 'dart:io';

import 'package:qiniu_flutter_sdk/qiniu_flutter_sdk.dart';

/// 七牛上传管理
class QiniuManager {
  static QiniuManager? _instance;

  static QiniuManager get instance {
    _instance ??= QiniuManager._();
    return _instance!;
  }

  QiniuManager._(){
    /// 添加上传进度监听
    putController.addProgressListener((percent) {
        log('上传进度监听 -> $percent');
    });
  }

  final Storage _storage = Storage();

  // 创建 Controller 对象
  PutController putController = PutController();

  /// 上传文件
  Future<String> uploadFile(String filePath, String token, String? key) async {
    var file = File(filePath);
    if(!file.existsSync()){
      return '';
    }
    if(token.isEmpty){
      return '';
    }
     var putResponse = await _storage.putFile(file, token,
        options: PutOptions(controller: putController,key: key));
     log('putResponse -> ${putResponse.rawData} , key-> ${putResponse.key}');
      // ..then((value) {
      //   log('value -> $value');
      // })
      // ..catchError((e) {
      //
      // });
    return putResponse.key ?? "";
  }


  /// 取消上传
  void cancelUpload() {
    putController.cancel();
  }
}
